﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TalksLog.Domain.Core;

namespace TalksLog.Infrastructure.EFRepository.IdentityGenerater
{
    public class IdentityGenerater : IIdentityGenerater
    {
        private static object _lockObj = new object();

        public int GetIdentity(string entityName)
        {
            int id = 0;

            lock(_lockObj)
            {
                using (EFDbContext context = new EFDbContext())
                {
                    EntityIdentity ei = context.EntityIdentites.Find(entityName);
                    if (ei == null)
                    {
                        ei = new EntityIdentity { EntityName = entityName, Identity = 1 };
                        context.EntityIdentites.Add(ei);
                    }
                    else
                    {
                        ei.Identity += 1;
                    }
                    context.SaveChanges();
                    id = ei.Identity;
                }
            }
            return id;
        }
    }
}
